package se.topshelf.golftracker.core.domain;

import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
 */
@Entity
@Table(name = "Continent", uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})})
public class Continent extends BaseEntity implements Comparable<Continent> {
    @NotNull
    private String code;
    @NotNull
    private String name;

    @OneToMany(mappedBy = "continent")
    @Sort(type = SortType.NATURAL)
    private SortedSet<Country> countries = new TreeSet<Country>();

    public Continent() {
    }

    public Continent(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public SortedSet<Country> getCountries() {
        return countries;
    }

    public void addCountry(Country country) {
        if (countries.contains(country)) {
            throw new IllegalArgumentException(MessageFormat.format(ILLEGAL_TO_REMOVE_ERROR_MESSAGE, country, this));

        }
        country.setContinent(this);
        countries.add(country);
    }

    void setCountries(SortedSet<Country> countries) {
        this.countries = countries;
    }

    @Override
    public String getGuiDescription() {
        return MessageFormat.format("{0} ({1})", name, code);
    }

    public int compareTo(Continent o) {
        return name.compareTo(o.getName());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Continent continent = (Continent) o;

        if (!name.equals(continent.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Continent");
        sb.append("{code='").append(code).append('\'');
        sb.append(", name='").append(name).append('\'');
        sb.append('}');
        return sb.toString();
    }
}
